from django.conf import  settings


import pika


class mq:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls)
        return cls._instance


    def __init__(self):

        if not hasattr(self, 'connection') or not hasattr(self, 'channel'):
            self.create_conn()
        else:
            if not self.connection.is_open or not self.channel.is_open:
                self.create_conn()


    def create_conn(self):
        host = settings.RABBITMQ['HOST']
        port = settings.RABBITMQ['PORT']
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=host, port='5672'))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue='hello')

    def publish(self, body):
        if not self.connection.is_open or not self.channel.is_open:
            self.create_conn()

        self.channel.basic_publish(exchange='', routing_key='hello', body=body)
        print('sent success')
